﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;


namespace Amarok.Agents
{
	/// <summary>
	/// </summary>
	internal sealed class InformationHandler<TMessage> :
		IHandler
		where TMessage : Information
	{
		// data
		private IAgent mAgent;


		#region ++ IHandler Interface ++

		/// <summary>
		/// </summary>
		void IHandler.Initialize(IAgent agent)
		{
			mAgent = agent;
		}

		/// <summary>
		/// </summary>
		void IHandler.Invoke(Message message)
		{
			var information = message as TMessage;

			#region (asserts)
			Debug.Assert(information != null,
				"Implementation Error: message must be cast-able to TMessage!");
			Debug.Assert(this.Callback != null || this.AsyncCallback != null,
				"Implementation Error: either Callback or AsyncCallback must be set!");
			#endregion

			if (this.Callback != null)
			{
				_InvokeSync(information);
			}
			else if (this.AsyncCallback != null)
			{
				_InvokeAsync(information);
			}
		}

		#endregion

		#region ++ Public Interface ++

		/// <summary>
		/// </summary>
		public Action<TMessage> Callback
		{
			get;
			private set;
		}

		/// <summary>
		/// </summary>
		public Func<TMessage, Task> AsyncCallback
		{
			get;
			private set;
		}


		/// <summary>
		/// </summary>
		public InformationHandler(Action<TMessage> callback)
		{
			Verify.NotNull(callback, "callback");
			this.Callback = callback;
		}

		/// <summary>
		/// </summary>
		public InformationHandler(Func<TMessage, Task> asyncCallback)
		{
			Verify.NotNull(asyncCallback, "asyncCallback");
			this.AsyncCallback = asyncCallback;
		}

		#endregion

		#region Implementation

		private void _InvokeSync(TMessage message)
		{
			try
			{
				#region (hook: started)
				AgentHooks.RaiseInformationHandlerStarted(mAgent, message, this.Callback);
				#endregion

				this.Callback(message);
			}
			catch (Exception exception)
			{
				_HandleException(message, exception);
				_CallInformationHandlerFailedHook(message, exception);

				#region (hook: failed)
				AgentHooks.RaiseInformationHandlerFailed(mAgent, message, this.Callback, exception);
				#endregion
			}
			finally
			{
				_CallInformationHandlerCompletedHook(message);

				#region (hook: finished)
				AgentHooks.RaiseInformationHandlerFinished(mAgent, message, this.Callback);
				#endregion
			}
		}

		private void _InvokeAsync(TMessage message)
		{
			#region (hook: started)
			AgentHooks.RaiseInformationHandlerStarted(mAgent, message, this.AsyncCallback);
			#endregion

			this.AsyncCallback(message)
				.ContinueWith(task =>
				{
					if (task.IsFaulted)
					{
						_HandleException(message, task.Exception.InnerException);
						_CallInformationHandlerFailedHook(message, task.Exception.InnerException);

						#region (hook: failed)
						AgentHooks.RaiseInformationHandlerFailed(mAgent, message, this.AsyncCallback, task.Exception.InnerException);
						#endregion
					}

					_CallInformationHandlerCompletedHook(message);

					#region (hook: finished)
					AgentHooks.RaiseInformationHandlerFinished(mAgent, message, this.AsyncCallback);
					#endregion
				},
				TaskContinuationOptions.ExecuteSynchronously);
		}

		private void _HandleException(Message message, Exception exception)
		{
			#region (tracing)
			{
				Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
					"*** WARNING: UNHANDLED INFORMATION HANDLER EXCEPTION:" +
					"\r\n  InformationType: {0}" +
					"\r\n  Information:     {1}" +
					"\r\n\r\n{2}",
					message.GetType(),
					message,
					Helper.FormatException(exception, CultureInfo.InvariantCulture)
				));
			}
			#endregion
		}

		private void _CallInformationHandlerFailedHook(Message message, Exception exception)
		{
			var action = DefaultDispatcherHooks.InformationHandlerFailed;

			if (action != null)
				action(message, exception);
		}

		private void _CallInformationHandlerCompletedHook(Message message)
		{
			var action = DefaultDispatcherHooks.InformationHandlerCompleted;

			if (action != null)
				action(message);
		}

		#endregion

	}
}
